//
//  XS_MyCourseItemVC.swift
//  XueDao
//
//  Created by 范东 on 2020/12/19.
//

import UIKit
import JXPagingView

enum XS_MyCourseItemVCType : Int {
    case all = 0
    case category = 1
    case free = 2
    case offline = 3
}

class XS_MyCourseItemVC: XS_BaseVC {
    
    var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    var type = XS_MyCourseItemVCType.all
    
    var courseRecordModel = XS_CourseItemM()

    @IBOutlet weak var collectionView: UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        shouldNavBarHidden = true
        collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: .bottomHeight + 16, right: 0)
        collectionView.register(UINib.init(nibName: "XS_MyCourseItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_MyCourseItemCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        
//        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(headerRefesh))
        collectionView.mj_footer = MJRefreshBackNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(footerRefesh))
//        requestCourseData(true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    @objc func headerRefesh(){
        requestCourseData(true)
    }
    
    @objc func footerRefesh(){
        requestCourseData(false)
    }


    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        collectionView.frame = view.bounds
    }
    
    func requestCourseData(_ isFirst: Bool = false){
        if isFirst {
            courseRecordModel.current = 0
            courseRecordModel.records.removeAll()
        }
        XS_NetWork.requestJson("/curriculum/queryUserCurriculum", parameters: ["pageNo" : courseRecordModel.current+1, "pageSize" : courseRecordModel.size,"isFree":type == .free ? "userFree" : "","curriculumForm":"","isCurriculumSeries":type == .category ? "yes": ""])
            .mapModel(type: XS_CourseItemM.self) // 返回 模型数组 和原始数据
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                model.records = self.courseRecordModel.records + model.records
                self.courseRecordModel = model
                if (self.collectionView != nil){
                    if model.records.count > 0 {
                        XD_BlankPageView.hiddenBlankPageView(superView: self.collectionView)
                        self.collectionView.reloadData()
                    } else {
                        XD_BlankPageView.blankPage(superView: self.collectionView, imgName: "缺省页_暂无内容", detailStr: "暂无内容~", bottomDetailStr: "")
                    }
                    self.collectionView.mj_header?.endRefreshing()
                    if model.current >= model.pages { // 没有更多
                        self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    }else{
                        self.collectionView.mj_footer?.endRefreshing()
                    }
                }
            }).disposed(by: disposeBag)
        
//        "isFree":"用户是否免费",（是：userFree，否：userPay）
//            "curriculumForm":"课程形式", (线下：offline,线上：online)
//            "isCurriculumSeries":"是否系列课"（是：yes，否：no）
//            "pageNo":"要查询的页码 不填默认为1",
//            "pageSize":"每页数据量,不填默认为10"
    
        
    }

}

extension XS_MyCourseItemVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return courseRecordModel.records.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_MyCourseItemCell", for: indexPath) as! XS_MyCourseItemCell
        cell.recentLabel.text = indexPath.item > 0 ? "" : "最近学习 "
        if indexPath.item < courseRecordModel.records.count {
            cell.model = courseRecordModel.records[indexPath.item]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: .screenWidth - 32, height: 104)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 16, left: 16, bottom: 16, right: 16)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 16
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 16
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let type = courseRecordModel.records[indexPath.item].curriculumType
        let id = courseRecordModel.records[indexPath.item].id
        if type == "seriesCurriculum" || type == "notSeriesCurriculum" {
            //线上课
            let vc = XS_KeChengVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }else if type == "offlineCurriculum"{
            //线下课
            let vc = XS_KCXianxiaVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }else if type == "live"{
            //直播课
            let vc = XS_KCZhiboVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}

extension XS_MyCourseItemVC: JXPagingViewListViewDelegate {
    public func listView() -> UIView {
        return view
    }

    public func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    public func listScrollView() -> UIScrollView {
        return collectionView
    }
}
